/*
 * Copyright (c) 2023-2025 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.starter.excel.kit;

import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;

/**
 * spring 上下文工具类
 *
 * @author zeng
 */
@Slf4j
@Lazy(false)
public class SpringContextKit
    implements BeanFactoryPostProcessor, ApplicationContextAware, DisposableBean {
  private static ConfigurableListableBeanFactory beanFactory;

  private static ApplicationContext applicationContext = null;

  /** 取得存储在静态变量中的ApplicationContext. */
  public static ApplicationContext getApplicationContext() {
    return applicationContext;
  }

  /** BeanFactoryPostProcessor, 注入Context到静态变量中. */
  @Override
  public void postProcessBeanFactory(ConfigurableListableBeanFactory factory)
      throws BeansException {
    SpringContextKit.beanFactory = factory;
  }

  /** 实现ApplicationContextAware接口, 注入Context到静态变量中. */
  @Override
  public void setApplicationContext(ApplicationContext applicationContext) {
    SpringContextKit.applicationContext = applicationContext;
  }

  public static ListableBeanFactory getBeanFactory() {
    return null == beanFactory ? applicationContext : beanFactory;
  }

  /** 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型. */
  public static <T> T getBean(Class<T> requiredType) {
    return getBeanFactory().getBean(requiredType);
  }

  /** 从静态变量applicationContext中取得Bean, {@code Map<Bean名称，实现类>} */
  public static <T> Map<String, T> getBeansOfType(Class<T> type) {
    return getBeanFactory().getBeansOfType(type);
  }

  /** 清除SpringContextKit中的ApplicationContext为Null. */
  public static void clearHolder() {
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("清除SpringContextKit中的ApplicationContext:" + applicationContext);
    }
    applicationContext = null;
  }

  @Override
  public void destroy() throws Exception {
    SpringContextKit.clearHolder();
  }
}
